<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./lib/dist/include-openlayers-local.js"></script>
    <style>
      .tooltip {
        position: relative;
        background: rgba(0, 0, 0, 0.5);
        border-radius: 4px;
        color: white;
        padding: 4px 8px;
        opacity: 0.7;
        white-space: nowrap;
      }
      .tooltip-static {
        background-color: #ffcc33;
        color: black;
        border: 1px solid white;
      }
    </style>
  </head>
  <body>
    <select id="selects">
      <option value="Point">点</option>
      <option value="LineString">线</option>
      <option value="Circle">圆</option>
      <option value="Square">正方形</option>
      <option value="Rectangle">矩形</option>
      <option value="Polygon">多边形</option>
    </select>
    <button onclick="active()">激活画笔</button>
    <button onclick="remove()">移除画笔</button>
    <button onclick="reset()">清除</button>
    <button onclick="checkele()">选择元素</button>
    <button onclick="delectcheckele()">清除选择</button>
    <button onclick="putele()">修改元素</button>
    <button onclick="saveele()">保存修改</button>
    <div id="map"></div>
    <script>
      var gaodeMapLayer = new ol.layer.Tile({
        title: '高德地图',
        source: new ol.source.XYZ({
          url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}',
          wrapX: false
        })
      })
      var map = new ol.Map({
        target: 'map',
        layers: [gaodeMapLayer],
        view: new ol.View({
          // projection: 'EPSG:4326',
          center: [0, 0],
          zoom: 5
        })
      })
      /* 1、创建画布--创建了一个空的矢量数据源 */
      // var source1 = new ol.source.Vector({})
      // var layer = new ol.layer.Vector({
      //   source: source1
      // })
      // map.addLayer(layer)
      /* 2、创建画笔 */
      // var draw = new ol.interaction.Draw({
      //   /* 画布在什么地方绘制 */
      //   source1,
      //   type: 'Point'
      // })
      // /* 3、将画笔添加到地图容器之上 */
      // map.addInteraction(draw)
      //创建一个wgs84球体对象

      //创建一个当前要绘制的对象
      var sketch
      var measureTooltipElement
      var measureTooltip
      let draw
      var source1 = new ol.source.Vector({})
      var typeValue
      var vectorLayer = new ol.layer.Vector({
        source: source1,
        style: new ol.style.Style({
          fill: new ol.style.Fill({
            color: '#0055ff'
          }),
          stroke: new ol.style.Stroke({
            color: '#00c033',
            width: 4
          }),
          image: new ol.style.Circle({
            radius: 5,
            fill: new ol.style.Fill({
              color: '#00c033'
            })
          })
        })
      })
      map.addLayer(vectorLayer)
      function active() {
        typeValue = document.getElementById('selects').value
        if (typeValue == 'Square') {
          draw = new ol.interaction.Draw({
            // 在哪个画布上绘制
            source: source1,
            // 绘制的类型
            type: 'Circle',
            geometryFunction: ol.interaction.Draw.createRegularPolygon(4)
          })
          map.addInteraction(draw)
          return
        } else if (typeValue == 'Rectangle') {
          draw = new ol.interaction.Draw({
            // 在哪个画布上绘制
            source: source1,
            // 绘制的类型
            type: 'LineString',
            geometryFunction: function (coordinates, geometry) {
              if (!geometry) {
                //多边形
                geometry = new ol.geom.Polygon(null)
              }
              var start = coordinates[0]
              var end = coordinates[1]
              geometry.setCoordinates([[start, [start[0], end[1]], end, [end[0], start[1]], start]])
              return geometry
            },
            maxPoints: 2
          })
          map.addInteraction(draw)
          return
        }
        draw = new ol.interaction.Draw({
          source: source1,
          type: typeValue
          // freehand: true
        })
        var listener
        draw.on(
          'drawstart',
          function (e) {
            sketch = e.feature
            var tooltipCoord = e.coordinate
            listener = sketch.getGeometry().on('change', function (evt) {
              var geom = evt.target //绘制几何要素
              var output
              if (geom instanceof ol.geom.Polygon) {
                output = formatArea(geom) //面积值
                tooltipCoord = geom.getInteriorPoint().getCoordinates() //坐标
              } else if (geom instanceof ol.geom.LineString) {
                output = formatLength(geom) //长度值
                tooltipCoord = geom.getLastCoordinate() //坐标
              }
              // console.log(output)
              // measureTooltipElement.innerHTML = output //将测量值设置到测量工具提示框中显示
              // measureTooltip.setPosition(tooltipCoord) //设置测量工具提示框的显示位置
            })
          },
          this
        )

        draw.on(
          'drawend',
          function (e) {
            // measureTooltipElement.className = 'tooltip tooltip-static' //设置测量提示框的样式
            // measureTooltip.setOffset([0, -7])
            // unset sketch
            sketch = null //置空当前绘制的要素对象
            // unset tooltip so that a new one can be created
            // createMeasureTooltip() //重新创建一个测试工具提示框显示结果
            //移除事件监听
            ol.Observable.unByKey(listener)
            // alert(output)
            //获取坐标值
            // console.log(e.feature.getGeometry().getCoordinates())
            // //获取中心点
            // console.log(e.feature.getGeometry().getCenter())
            // //获取半径
            // console.log(e.feature.getGeometry().getRadius())
          },
          this
        )
        map.addInteraction(draw)
      }
      function remove() {
        map.removeInteraction(draw)
      }
      function reset() {
        source1.clear()
      }
      var output
      var formatLength = function (line) {
        var length
        var sphere = new ol.Sphere()

        //若使用测地学方法测量
        var sourceProj = map.getView().getProjection() //地图数据源投影坐标系
        length = sphere.getLength(line, { projection: sourceProj, radius: 6378137 })

        if (length > 100) {
          output = Math.round((length / 1000) * 100) / 100 + ' ' + 'km' //换算成KM单位
        } else {
          output = Math.round(length * 100) / 100 + ' ' + 'm' //m为单位
        }
        return output //返回线的长度
      }
      var formatArea = function (polygon) {
        var area
        var sphere = new ol.Sphere()

        //若使用测地学方法测量
        var sourceProj = map.getView().getProjection() //地图数据源投影坐标系
        var geom = /** @type {ol.geom.Polygon} */ (polygon.clone().transform(sourceProj, 'EPSG:4326')) //将多边形要素坐标系投影为EPSG:4326
        area = Math.abs(sphere.getArea(geom, { projection: sourceProj, radius: 6378137 })) //获取面积
        output = Math.round(area * 100) / 100 + ' ' + 'km<sup>2</sup>' //m为单位
        return output //返回多边形的面积
      }
      var select
      function checkele() {
        select = new ol.interaction.Select({
          filter: (feature, layer) => {
            return layer === vectorLayer
          }, //选择图层
          layers: [vectorLayer], //选择图层
          condition: ol.events.condition.singleClick, //选择的触发
          addCondition: ol.events.condition.platformModifierKeyOnly, //ctrl加点击 选择元素
          // removeCondition: ol.events.condition.shiftKeyOnly, //shift加点击,取消选择元素
          toggleCondition: ol.events.condition.singleClick, // 点击实现多选
          multi: false, // 默认false。设置是否支持穿透性多选。如：设为true，那么点击的时候将会选择所点位置的全部图层。设为false只会选择最上面那个
          style: new ol.style.Style({
            radius: 10,
            fill: new ol.style.Fill({
              color: '#2E5BB3' //被选中的图层的样式
            }),
            stroke: new ol.style.Stroke({
              color: '#E71B14',
              width: 4
            }),
            image: new ol.style.Circle({
              radius: 5,
              fill: new ol.style.Fill({
                color: 'blue'
              }),
              stroke: new ol.style.Stroke({
                color: '#A4CDFF',
                width: 2
              })
            })
          })
          // hitTolerance: 100  //范围内的元素
        })
        map.addInteraction(select)
      }
      function delectcheckele() {
        select.getFeatures().clear() //清除选择
        // map.removeInteraction(select)
        select.setActive(false) //禁用select
      }
      var modify
      function putele() {
        modify = new ol.interaction.Modify({
          features: select.getFeatures()
        })
        map.addInteraction(modify)
      }
      function saveele() {
        select.getFeatures().clear()
        map.removeInteraction(modify)
        map.removeInteraction(select)
      }
    </script>
  </body>
</html>
